<?php

declare(strict_types=1);

namespace App\Service;

/**
 * 外部支付服务管理
 * Class AdvancePayService
 * @package App\Service
 */
class AdvancePayService extends BaseService
{

    /**
     * 生成外部支付单号
     * @param array $params
     * @return string
     */
    public function generateOuterSn(array $params): string
    {
        // 验证参数
        if (empty($params['order_sn']) || empty($params['pay_type']) || empty($params['pay_method']) || empty($params['type'])) {
            return "";
        }
        if (!in_array($params['pay_type'], ['alipay', 'wxpay'])) {
            return "";
        }
        if (!in_array($params['pay_method'], ['app', 'scan', 'miniapp', 'web'])) {
            return "";
        }
        $where_data = [
            'platform' => $params['pay_type'],
            'pay_method' => $params['pay_method'],
            'order_sn' => $params['order_sn'],
            'type' => $params['type'] == 1 ? 1 : 2
        ];
        $instance = $this->getModelInstance()->where($where_data)->first();
        if (empty($instance)) {
            $instance = $this->getModelInstance();
            $instance->order_sn_re = $params['order_sn'] . "RE" . mt_rand(1000000, 9999999);
            $instance->create_time = time();
        }
        foreach ($where_data as $f => $v) {
            $instance->$f = $v;
        }
        if (!$instance->save()) {
            return "";
        }
        return $instance->order_sn_re;
    }

    /**
     * 根据回调获取单号、类型
     * @param string $order_sn_re
     * @param string $platform
     * @param string $pay_method
     * @return array
     */
    public function getRecordByNotify(string $order_sn_re, string $platform, string $pay_method): array
    {
        if (empty($order_sn_re) || empty($platform) || empty($pay_method)) {
            return [];
        }
        $where = [
            'order_sn_re' => $order_sn_re,
            'platform' => $platform,
            'pay_method' => $pay_method
        ];
        $record = $this->getModelInstance()->where($where)->first();
        if (empty($record)) {
            return [];
        }
        return $record->toArray();
    }

    /**
     * 获取订单支付类型
     * @param string $outer_sn
     * @return string
     */
    public function getPayTypeByOuterSN(string $outer_sn): string
    {
        $pay_type = $this->getModelInstance()->where(['order_sn_re' => $outer_sn])->value('platform');
        return empty($pay_type) ? "" : $pay_type;
    }
}